from django.contrib.auth.models import AnonymousUser
from rest_framework import serializers

from activity.models import Activity
from headline.models import Category, News, Comment
from question.models import Label
from users.models import User


class CategoryListSerializer(serializers.ModelSerializer):
    """新闻专栏分类序列化器"""
    class Meta:
        model = Category
        fields = ("id", "name", 'url', 'description')
        extra_kwargs = {
            'id': {'read_only': True},
            'url': {'write_only': True},
            'description': {'write_only': True},
        }

    def create(self, validated_data):
        """创建专栏实例对象"""
        sequence = Category.objects.count() + 1
        validated_data['sequence'] = sequence
        return super(CategoryListSerializer, self).create(validated_data)


class AuthorSerializer(serializers.ModelSerializer):
    """新闻作者序列化器"""
    class Meta:
        model = User
        fields = ("id", "username", 'avatar')


class NewsListSerializer(serializers.ModelSerializer):
    """首页新闻列表序列化器"""
    author = AuthorSerializer(read_only=True)

    class Meta:
        model = News
        fields = ("id", "title", "digest", "author", "create_time")
        # {
        #     'id': '新闻id'，
        # 'title': '新闻标题'，
        # 'digest': '新闻摘要'，
        # 'author_id': '作者id',
        # 'author_name': '新闻作者',
        # 'create_time': '发布日期',
        # 'is_vip': '是否VIP'
        # },


class ActivityList2Serializer(serializers.ModelSerializer):
    """首页活动列表序列化器"""
    # [
    #     {
    #         'id': '活动id'，
    # 'image_url': '活动图片url'
    # },
    # {
    #     'id': '活动id'，
    # 'image_url': '活动图片url'
    # }
    # ...
    # ]
    class Meta:
        model = Activity
        fields = ("id", "image_url")


class AnswersListSerializer(serializers.ModelSerializer):
    """首页热门回答序列化器"""
    class Meta:
        # TODO 热门问答数据库模型类 待处理
        pass


class CommentSerializer(serializers.ModelSerializer):
    """评论序列化器"""
    news_id = serializers.CharField(label='新闻id', write_only=True)
    parent_id = serializers.CharField(label='父评论id', write_only=True, required=False)
    user = AuthorSerializer(read_only=True)

    class Meta:
        model = Comment
        fields = ("id", "content", "news_id", "parent_id", 'user')
        read_only_fields = ('id',)

    def validate(self, attrs):
        news_id = attrs['news_id']
        parent_id = attrs.get('parent_id', None)

        try:
            is_comment = News.objects.get(id=news_id).is_comment
            if not is_comment:
                raise serializers.ValidationError('新闻禁止评论')
            if parent_id:
                Comment.objects.filter(id=parent_id, news_id=news_id).get()
        except Comment.DoesNotExist:
            raise serializers.ValidationError('参数错误')
        else:
            return attrs

    def create(self, validated_data):

        user = self.context['request'].user

        if isinstance(user, AnonymousUser):
            raise serializers.ValidationError('请登录后操作')

        validated_data['user'] = user
        comment = super(CommentSerializer, self).create(validated_data)
        # 新增评论对应的新闻评论量加１
        comment.news.comment_count += 1
        return comment


class Comment2Serializer(serializers.ModelSerializer):
    """评论序列化器"""
    subs = CommentSerializer(many=True, read_only=True)
    user = AuthorSerializer(read_only=True)

    class Meta:
        model = Comment
        fields = ("id", "content", 'user', 'subs')
        read_only_fields = ('id', )


class NewsDetailSerializer(serializers.ModelSerializer):
    """新闻详情序列化器"""
    # [{
    #     'id': '新闻id'，
    # 'title': '新闻标题',
    # 'content': '新闻内容',
    # 'create_time': '发布时间',
    # 'source': '新闻来源',
    # {
    #     'comment': [
    #         {
    #             'id': '评论id'，
    # 'content': '评论内容',
    # 'parent_id': '父评论id'
    # }
    # ...
    # ]
    comment_set = Comment2Serializer(read_only=True, many=True)
    label_id = serializers.ListField(label='标签id', write_only=True)
    category_id = serializers.CharField(label='分类id', write_only=True)

    class Meta:
        model = News
        fields = ("id", "title", "create_time", "source", 'comment_set', "comment_count", 'category_id',
                  'label_id', 'content')
        extra_kwargs = {
            'id': {'read_only': True},
            'create_time': {'read_only': True},
            'source': {'read_only': True},
            'comment_set': {'read_only': True},
            'comment_count"': {'read_only': True},
        }

    def validate(self, attrs):
        """验证分类和标签"""
        category_id = attrs.pop('category_id')
        label_id = set(attrs.pop('label_id'))

        try:
            attrs['category'] = Category.objects.get(id=category_id)
            attrs['label'] = Label.objects.filter(id__in=label_id)
        except Category.DoesNotExist or Label.DoesNotExist:
            raise serializers.ValidationError('参数异常')
        else:
            return attrs

    def create(self, validated_data):
        """创建头条"""
        user = User.objects.get(id=1)

        if isinstance(user, AnonymousUser):
            raise serializers.ValidationError('请登录后操作')
        validated_data['author'] = user
        return super(NewsDetailSerializer, self).create(validated_data)


class AuthorSerializer2(serializers.ModelSerializer):
    """新闻作者序列化器"""
    class Meta:
        model = User
        # 用户要返回 名字 id 头像
        fields = ("id", "username", "avatar")


class AuthorRecentSerializer(serializers.ModelSerializer):
    """
    作者动态序列化器
    返回当前作者的发布新闻 限制4条
    """
    # {
    #     'id': '作者id',
    #     'author_name': '作者名字',
    #     'recent': [
    #         {
    #             'id': '新闻id'：
    # 'title': '新闻标题'
    # }，
    # {
    #     'id': '新闻id'：
    # 'title': '新闻标题'
    # }，
    # ...
    # ]
    #
    # }
    author = AuthorSerializer2(read_only=True)

    class Meta:
        model = News
        fields = ("id","author","title")


class HotRecommendSerializer(serializers.ModelSerializer):
    """
    热门回答 序列化器
    返回字段 新闻id 和 title
    """
    class Meta:
        model = News
        fields = ("id", "title")



